#!/usr/bin/python
from cryptos import *
import json

coins = {
    'bch': BitcoinCash,
    'btc': Bitcoin,
    'dash': Dash,
    'doge': Doge,
    'ltc': Litecoin
}

if len(sys.argv) == 1:
    print("pybtctool <command> <arg1> <arg2> ...")
else:
    coin = Bitcoin
    testnet = False
    cmdargs, preargs, kwargs = [], [], {}
    i = 2
    # Process first arg tag
    if sys.argv[1] == '-s':
        preargs.extend(re.findall(r'\S\S*', sys.stdin.read()))
    elif sys.argv[1] == '-B':
        preargs.extend([sys.stdin.read()])
    elif sys.argv[1] == '-b':
        preargs.extend([sys.stdin.read()[:-1]])
    elif sys.argv[1] == '-j':
        preargs.extend([json.loads(sys.stdin.read())])
    elif sys.argv[1] == '-J':
        preargs.extend(json.loads(sys.stdin.read()))
    else:
        i = 1
    while i < len(sys.argv):
        if sys.argv[i] == '--testnet':
            testnet = True
            i += 1
        elif sys.argv[i] == '--coin':
            coinname = sys.argv[i+1].lower()
            try:
                coin = coins[coinname]
            except KeyError:
                raise Exception('Coin %s not recognised. Choose from: %s ' % (coin, ','.join(coins.keys())))
            i += 2
        elif sys.argv[i][:2] == '--':
            kwargs[sys.argv[i][2:]] = sys.argv[i+1]
            i += 2
        else:
            cmdargs.append(sys.argv[i])
            i += 1
    cmd = cmdargs[0]
    args = preargs + cmdargs[1:]
    try:
        c = coin(testnet=testnet)
        o = getattr(c, cmd)(*args, **kwargs)
    except AttributeError:
        o = vars()[cmd](*args, **kwargs)
    if isinstance(o, (list, dict)):
        print(json.dumps(o))
    else:
        print(o)
